package com.redis.queen;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import redis.clients.jedis.Jedis;

import java.lang.reflect.Type;
import java.util.UUID;

public class RedisBlockQueen<T> {
    private static final String BASE_QUEEN_KEY = "QUEEN_KEY:";
    static final long DEFAULT_TIMEOUT = 0L;

    private Jedis jedis;

    private String queenName;

    private String queenKey;

    private Type type = new TypeReference<TaskItem<T>>() {
    }.getType();

    public RedisBlockQueen(Jedis jedis, String queenName) {
        this.jedis = jedis;
        this.queenName = queenName;
        this.queenKey = BASE_QUEEN_KEY + queenName;
    }

    public RedisBlockQueen(String host, int port, String queenName) {
        this(new Jedis(host, port), queenName);
    }

    public void put(T msg) {
        TaskItem<T> taskItem = new TaskItem<>(UUID.randomUUID().toString(), msg);
        jedis.rpush(queenKey, JSON.toJSONString(taskItem));
    }

    public T get() {
        String value = jedis.blpop(DEFAULT_TIMEOUT, queenKey).getValue();
        TaskItem<T> taskItem = JSON.parseObject(value, type);
        return taskItem.getMsg();
    }

    public void close() {
        if (jedis == null) {
            return;
        }
        jedis.close();
    }
}
